package com.magic.service;

import java.util.List;
import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.magic.entity.user.Flower;
import com.magic.entity.user.User;
import com.magic.redis.jedis.JedisService;
import com.magic.repository.IFlowerRepository;
import com.magic.repository.IUserRepository;
import com.magic.result.Result;
import com.magic.service.mobile.SmsService;
import com.magic.util.CodeUtil;
import com.magic.vo.ForgetPassword;
import com.magic.vo.MobileRegister;

/**
 * ClassName: RegisterService <br/>
 * Function: 注册service. <br/>
 * date: 2018年10月16日 上午9:37:48 <br/>
 * 
 * @author lishuai11
 * @version
 * @since JDK 1.8
 */
@Service("registerServie")
public class RegisterService {

	private static final Logger logger = LoggerFactory.getLogger(RegisterService.class);

	@Autowired
	JedisService jedisService;

	@Autowired
	SmsService smsService;

	@Autowired
	IUserRepository userRepository;

	@Autowired
	IFlowerRepository flowerRepository;

	@Value("${sms.expire}")
	private int expire;

	/**
	 * 
	 * code:(获取验证码). <br/>
	 * 
	 * @author lishuai11
	 * @param mobile
	 * @return
	 * @since JDK 1.8
	 */
	public synchronized Result code(String mobile) {
		try {
			if (jedisService.isExist(mobile)) {
				return Result.fail(Result.CLIENT_ERROR, "禁止重复发送：请2分钟后重新发送");
			}
			String code = code();
			int expire = redisCache(mobile, code);
			String state = smsService.sendSms(mobile, code);
			if (state.equals("0")) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("mobile", mobile);
				jsonObject.put("expire", expire);
				return Result.success("发送成功", jsonObject);
			} else {
				jedisService.delete(mobile);
				return Result.fail(Result.SERVER_ERROR, "短信发送失败");
			}
		} catch (Exception e) {
			logger.error("RegisterService.code()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	/**
	 * 
	 * mobileRegister:(手机号码注册). <br/>
	 * 
	 * @author lishuai11
	 * @param mobileRegister
	 * @return
	 * @since JDK 1.8
	 */
	@Transactional
	public synchronized Result mobileRegister(MobileRegister mobileRegister) {
		try {
			User user = findByName(mobileRegister.getMobile());
			if (user != null) {
				return Result.fail(Result.CLIENT_ERROR, "用户名已注册");
			}
			// ②：判断验证码是否超时
			if (!jedisService.isExist(mobileRegister.getMobile())) {
				return Result.fail(Result.CLIENT_ERROR, "验证码超时");
			}
			// ③：判断验证码是否正确
			String param = jedisService.get(mobileRegister.getMobile());
			if (!param.equals(mobileRegister.getCode())) {
				return Result.fail(Result.CLIENT_ERROR, "验证码错误");
			}
			// ④：信息校验成功，注册成功
			String password = DigestUtils.md5Hex(mobileRegister.getPassword());
			user = new User(mobileRegister.getMobile(), password);
			user = userRepository.save(user);
			user.setUserCode(CodeUtil.code(user.getUserId()));
			user = userRepository.save(user);
			jedisService.delete(mobileRegister.getMobile());
			// ⑤：花种初始化
			flowerRepository.save(new Flower(user.getUserId()));
			return Result.success("注册成功", user);
		} catch (Exception e) {
			logger.error("RegisterService.mobileRegister()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	public Result forgetPassword(ForgetPassword forgetPassword) {
		try {
			User user = findByName(forgetPassword.getMobile());
			if (user == null) {
				return Result.fail(Result.CLIENT_ERROR, "用户不存在");
			} else {
				// ①：判断验证码是否超时
				if (!jedisService.isExist(forgetPassword.getMobile())) {
					return Result.fail(Result.CLIENT_ERROR, "验证码超时");
				}
				// ②：判断验证码是否正确
				String param = jedisService.get(forgetPassword.getMobile());
				if (!param.equals(forgetPassword.getCode())) {
					return Result.fail(Result.CLIENT_ERROR, "验证码错误");
				}
				String password = DigestUtils.md5Hex(forgetPassword.getSecondPassword());
				if (user.getPassword().equals(password)) {
					return Result.fail(Result.CLIENT_ERROR, "密码与之前一致");
				}
				user.setPassword(password);
				user = userRepository.save(user);
				jedisService.delete(forgetPassword.getMobile());
				return Result.success("新密码设置成功");
			}
		} catch (Exception e) {
			logger.error("RegisterService.forgetPassword()方法异常{}:{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	/**
	 * 
	 * code:(生成验证码). <br/>
	 * 
	 * @author lishuai8
	 * @return
	 * @since JDK 1.8
	 */
	private String code() {
		Random random = new Random();
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < 6; i++) {
			builder.append(random.nextInt(10));
		}
		return builder.toString();
	}

	/**
	 * 
	 * redisCache:(缓存验证码). <br/>
	 * 
	 * @author lishuai11
	 * @param mobile
	 * @param code
	 * @return
	 * @throws Exception
	 * @since JDK 1.8
	 */
	private int redisCache(String mobile, String code) throws Exception {
		String key = mobile;
		int time = expire;
		jedisService.setex(key, time, code);
		return time;
	}

	public User findByName(String userName) {
		List<User> users = userRepository.findByUserName(userName);
		if (users != null && !users.isEmpty()) {
			return users.get(0);
		}
		return null;
	}
}
